const fs = require('fs');
const path = require('path');
const archiver = require('archiver');

export default class Zip {
  private readonly source: string = '';
  public constructor(source?: string) {
    if (source) this.source = source;
    else {
      this.source = path.join(__dirname, '/tmp');
    }
  }
  public async compactFile(file: string = '') {
    return await new Promise((resolve, reject) => {
      const output = fs.createWriteStream(
        path.join(this.source, '../', file + '.zip')
      );
      const archive = archiver('zip', {
        zlib: { level: 9 },
      });

      // on
      output.on('close', function () {
        resolve('zip file success!');
      });
      archive.on('error', function (err) {
        reject(err);
      });
      // zip
      archive.pipe(output);
      archive.file(path.join(this.source, file), {
        name: path.basename(path.join(this.source, file)),
      });
      archive.finalize();
    });
  }

  public async compactFolder(folder: string = '') {
    return await new Promise((resolve, reject) => {
      const output = fs.createWriteStream(
        path.join(this.source, '../', folder + '.zip')
      );
      const archive = archiver('zip', {
        zlib: { level: 9 },
      });

      // on
      output.on('close', function () {
        resolve('zip file success!');
      });
      archive.on('error', function (err) {
        reject(err);
      });
      // zip
      archive.pipe(output);
      archive.directory(path.join(this.source, folder), false);
      archive.finalize();
    });
  }
}
